// pages/index/showdetails/showdetails.js
const utils = require('../../../utils/util.js');
const glob = getApp().globalData;
const nim = require('../../../utils/chatroom.js');
import {discuss, defaultPic, recoreStart, stopRecord,playAudio,playAudioGif} from "../../../utils/imgbase64.js";
const screen = wx.getSystemInfoSync();
const recorderManager = wx.getRecorderManager();
const innerAudioContext = wx.createInnerAudioContext();
const h = screen.windowWidth/750;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //基本信息
    tid:"",
    name:"",
    image:"",
    initiator:"",
    time:"",
    //是否收起
    isShow: true,
    //输入状态
    isAudio:false,
    audioTip:'按住 说话',
    tapbg: "#f9f7f8",
    tapcolor:'#666',
    isPlay:false,
    currurl:'',
    arrow: 'icon-jiantoushang',
    msgscrollheight:screen,
    warph:0,
    // 用户身份
    role:0,
    animationData:{},
    // 项目方输入内容
    adminval:'',
    //项目方发送按钮
    adminDis:false,
    // 用户输入内容
    userText:"",
    // 用户评论按钮
    userDis:true,
    //是否支持即时通讯
    canUser:true,
    //项目方消息数组
    adminData:[],
    //气泡消息数组
    bubbleList:[],
    //是否录音
    isRecord:false,
    //录音状态
    recordState:'start',
    //发送状态
    sendState:'手指上划，取消发送',
    //提示背景色
    ubbg:'none',
    //是否发送
    isSendAudio:false,
    //历史消息页码
    lid: "",
    //当前显示时间戳
    showTime:0,
    //路演是否完成
    isComplete:false,
    cgnames:[]
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
      if(options.type =="old"){
        this.setData({
          isComplete:true
        })
      }
      this.setData({
         queryId:options.id,
         discussimg:discuss,
         defaultPic,
         recoreStart,
         stopRecord,
      })
      wx.showLoading({
          title: '加载中',
      })
      this.tempFilePath="";
  },
  //切换输入
  changeInpType:function(){
     this.setData({
         isAudio:!this.data.isAudio
     })
  },
  //长按录音
  stratRecord:function(e){
    this.recordTimer = setTimeout(()=>{
        this.touchStartY = e.touches[0].clientY;
        this.setData({
            audioTip: '松开 结束',
            tapbg: "#d0d1d1",
            tapcolor: '#666',
            isRecord: true,
        })
        let options = {
            sampleRate: 44100,
            numberOfChannels: 1,
            encodeBitRate: 192000,
            format: 'mp3',
            frameSize: 50
        }
        wx.authorize({
            scope: 'scope.record',
            success: () => {
                // 用户已经同意小程序使用录音功能，后续调用 wx.startRecord 接口不会弹窗询问
                recorderManager.start(options);
            }
        })
    },500)
  },
  //手指移动
  recordMove:function(e){
     let nowTouchY = e.changedTouches[0].clientY;
     let s = Math.abs(nowTouchY - this.touchStartY);
     if(s>120){
         this.setData({
             recordState: 'stop',
             //发送状态
             sendState: '松开手指，取消发送',
             //提示背景色
             ubbg:'#962725',
             //是否发送
             isSendAudio: false
         })
     }else{
         this.setData({
             recordState: 'start',
             //发送状态
             sendState: '手指上划，取消发送',
             //提示背景色
             ubbg: 'none',
             //是否发送
             isSendAudio: true
         })
     }
  },
 //触摸中断
  cancelRecord:function(){
      clearTimeout(this.recordTimer);
      this.setData({
          audioTip: '按住 说话',
          tapbg: "#f9f7f8",
          tapcolor: '#666',
          isRecord: false,
          recordState: 'start',
          //发送状态
          sendState: '手指上划，取消发送',
          //提示背景色
          ubbg: 'none'
      })
      recorderManager.stop();
      this.tempFilePath = "";
  },
  //松开结束
  endRecord:function(e){
      clearTimeout(this.recordTimer);
      this.setData({
          audioTip: '按住 说话',
          tapbg: "#f9f7f8",
          tapcolor: '#666',
          isRecord: false,
          recordState: 'start',
          //发送状态
          sendState: '手指上划，取消发送',
          //提示背景色
          ubbg: 'none'
      })
      recorderManager.stop();
  },
  //发送音频消息
  sendAudio:function(path){
      console.log(path)
      let role = { role: 2 };
      glob.nim.sendFile({
          type: 'audio',
          wxFilePath: path,
          custom: JSON.stringify(role),
          done: this.sendFileMsg
      })
      this.tempFilePath="";
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    //判断版本兼容
    wx.getSystemInfo({
        success:(res)=>{
            let arr = res.SDKVersion.split('.')
            let num = parseInt(arr[0]) * 10 + parseInt(arr[1])
            if (num < 19) {
                this.setData({
                    canUser:false
                })
            }
        }
    })
    this.pageScroll = 0;
    //音频播放停止
    innerAudioContext.onStop((res)=>{
        this.setData({
            currurl:''
        })
    })
    //音频播放结束
    innerAudioContext.onEnded((res)=>{
        this.data.adminData.map((res, index) => {
            if (innerAudioContext.src == this.data.currurl) {
                res.audioImg = playAudio;
            }
        })
        this.setData({
            currurl: '',
            adminData:this.data.adminData
        })
    })
    //录音停止，获取文件路径
    recorderManager.onStop((res) => {
        let path = res.tempFilePath;
        if (path&& this.data.isSendAudio == true) {
            this.sendAudio(path);
        }
        this.data.isSendAudio = true;
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let app = getApp();
    app.loginState();
    this.setData({
        warph:575*h
    })
    let animation = wx.createAnimation({
        duration: 700,
        timingFunction: 'ease',
    })
    this.animation = animation;
    this.animation.height(this.data.warph).step();
    this.setData({
        isShow: true,
        arrow: 'icon-jiantoushang',
        animationData: this.animation.export()
    })
     this.isTop = true;
     utils.ajax(glob.ROOT_URL + "demosts/" + this.data.queryId, {
         method: 'get',
         header: {
             Accept: "application/vnd.dct.v1+json"
         },
         data: {
             uid: wx.getStorageSync('user_info').uid
         }
     }, res => {
         wx.hideLoading()
         if (res.state == 1) {
             let data = res.data;
             this.title = data.title;
             wx.setNavigationBarTitle({
                 title: data.title
             })
             this.setData({
                 tid: data.id,
                 name: data.title,
                 image: data.image,
                 time: data.time,
                 initiator: data.initiator,
                 role: data.role,
                 cgnames: data.cgnames
             })
             this.roomid = data.roomid;
             this.room_addr = data.room_addr;
             console.log("开始连接")
             this.chatRoomInit(data.roomid, data.room_addr);
             console.log(this.roomid,this.room_addr)
         } else {
             wx.showToast({
                 title: '获取数据失败，请重试',
                 icon: 'none'
             })
         }
     }, err => {
         wx.hideLoading()
         wx.showToast({
             title: '获取数据失败，请重试',
             icon: 'none'
         })
     })
  },
  slideToggle: function () {
      if (this.data.isShow) {
          this.animation.height(0).step()
          this.setData({
              isShow: false,
              arrow: 'icon-jiantouxia',
              animationData: this.animation.export(),
              msgscrollheight:1000
          })
      } else {
          this.animation.height(this.data.warph).step()
          this.setData({
              isShow: true,
              arrow: 'icon-jiantoushang',
              animationData: this.animation.export(),
              msgscrollheight:430
          })
      }
  },
  //跳转文件列表
  openfilepage: function () {
      if (this.data.tid != "" && this.data.tid != undefined && this.data.tid != null) {
          wx.navigateTo({
              url: '../../itemfile/itemfile?id=' + this.data.tid,
          })
      }
  },
//   //记录与滚动
//   viewMove:function(e){
//     this.pageStartY = e.touches[0].clientY;
//   },
//   viewScroll:function(e){
//       this.pageEndY = e.changedTouches[0].clientY;
//       let s = this.pageEndY - this.pageStartY;
//       let pageTop = this.pagescroll;
//       if(this.data.isRecord ==false){
//           let top = pageTop - s;
//          wx.pageScrollTo({
//              scrollTop:top,
//              duration:0
//          })
//       }
//   },
  //云信聊天室模块
  //初始化聊天室
  chatRoomInit:function(roomid,addrs){
      if (this.data.canUser==false){
        return false;
      }
      let user = wx.getStorageSync('user_info');
      new nim.Chatroom({
          account:user.accid,
          token:user.token,
          roomId: roomid,
          roomAddr:addrs,
          onconnect:this.roomConnect,
          onerror: this.roomError,
          onmsgs: this.roomMsgs,
          ondisconnect:res=>{
          }
      })
  },
  //聊天室连接成功
  roomConnect: function (info) {
    console.log("连接成功")
    this.getHistory(1,true)
    this.getHistory(1,true,"0");
  },
  //聊天室连接失败
  roomError:function(err){
      console.log('err', err)
  },
  //聊天室收到消息
  roomMsgs: function (msgs){
    if (msgs[0].type =="notification"){
    } else if (msgs[0].type == "image" || msgs[0].type=="audio"){
        if(msgs[0].type=='audio'){
            let dur = Math.ceil(Number(msgs[0].file.dur)/1000);
            msgs[0].file.dur = dur;
            msgs[0].audioImg = playAudio;
        }
        let time = Number(msgs[0].userUpdateTime);
        if(time-this.data.showTime>=300){
            msgs[0].long = "1";
            msgs[0].date = utils.showMsgDate(time);
        }
        this.data.adminData.push(msgs[0]);
        if (this.data.cgnames.length > 0) {
          this.data.adminData.map((item, index) => {
            let oldid = item.from;
            this.data.cgnames.map((item2, index2) => {
              console.log(oldid)
              if (item2.accid == oldid) {
                this.data.adminData[index].fromNick = item2.tsname;
              }
            })
          })
        }
        this.setData({
            adminData: this.data.adminData
        })
        this.scrollBottom();
    }else{
        let role = JSON.parse(msgs[0].custom);
        if (role.role == 0){
            if (this.data.bubbleList.length >= 3) {
                this.data.bubbleList.shift();
            }
            this.data.bubbleList.push(msgs[0]);
            this.setData({
                bubbleList: this.data.bubbleList
            })
        }else{
          this.data.adminData.push(msgs[0]);
          if (this.data.cgnames.length > 0) {
            this.data.adminData.map((item, index) => {
              let oldid = item.from;
              this.data.cgnames.map((item2, index2) => {
                console.log(oldid)
                if (item2.accid == oldid) {
                  this.data.adminData[index].fromNick = item2.tsname;
                }
              })
            })
          }
          this.setData({
            adminData: this.data.adminData
          })
          this.scrollBottom();
        }
    }
  },
  //聊天室发送消息
  sendRoomMsgs:function(opt){
     //发送文本消息
     if(opt.type == 'text'){
         let msg = {
             text:opt.content,
             idClient:opt.idClient||"",
             resend:opt.resend||false,
             custom:JSON.stringify(opt.custom),
             done:this.sendMsgsResult
         }
         glob.nim.sendText(msg)
     }
  },
  //消息发送结果
  sendMsgsResult:function(err,msg){
    console.log(err)
    if(!err){
        console.log(msg)
        let role = JSON.parse(msg.custom).role;
        let user = wx.getStorageSync("user_msg");
        //验证身份，0为普通用户
        if(role==0){
            msg.fromNick = user.nickname;
            msg.fromAvatar = user.avatar;
            this.data.bubbleList.push(msg);
            if (this.data.bubbleList.length > 3) {
                this.data.bubbleList.shift();
            }
            this.setData({
                bubbleList: this.data.bubbleList
            })
        }else{
            let time = Number(msg.userUpdateTime);
            console.log(time, this.data.showTime);
            if (time - this.data.showTime >= 300) {
                msg.showTime = "1";
                msg.date = utils.showMsgDate(time);
            }
            msg.fromNick = user.nickname;
            msg.fromAvatar = user.avatar;
            this.data.adminData.push(msg);
            if (this.data.cgnames.length > 0) {
              this.data.adminData.map((item, index) => {
                let oldid = item.from;
                this.data.cgnames.map((item2, index2) => {
                  console.log(oldid)
                  if (item2.accid == oldid) {
                    this.data.adminData[index].fromNick = item2.tsname;
                  }
                })
              })
            }
            this.setData({
                adminData:this.data.adminData
            })
            this.scrollBottom();
        }
    }else{
        wx.showToast({
            title: '消息发送失败，请重试~',
            icon:"none"
        })
        glob.nim.connect();
    }
  },
  //监听页面滚动
  onPageScroll:function(e){
     this.pagescroll = e.scrollTop;
     if(this.pagescroll<=0 && this.isTop == true){
         //滚动到顶部获取历史记录
         this.getHistory("",false)
     }
  },
  //获取消息历史记录
  getHistory:function(page,bol,f){
      this.isTop = false;
      let to = f||"1";
      wx.showLoading();
      utils.ajax(glob.ROOT_URL + 'demosts/' + this.data.queryId + '/replies', {
          header: {
              "Accept": "application/vnd.dct.v1+json"
          },
          data: {
              lid: this.data.lid,
              from: to,
              uid:wx.getStorageSync("user_info").uid
          }
      }, res => {
          wx.hideLoading();
          this.isTop = true;
          if (res.state == "1") {
              if (res.data.length < 1) {
                if (bol == false){
                    wx.showToast({
                          title: '没有更多历史记录~',
                          icon: "none"
                    })
                }
              } else {
                  let data = [];
                  if(to =="1"){
                      data = res.data.reverse();
                      this.setData({
                          lid: data[data.length - 1].id
                      })
                  }else{
                      data = res.data;
                  }
                  data.map((item,index)=>{
                      if (to=="1"){
                         if (item.type == "image" || item.type == "audio") {
                             item.file = JSON.parse(item.file)
                         }
                         if (item.type == "audio") {
                             item.file.dur = Math.ceil(Number(item.file.dur) / 1000);
                             item.audioImg = playAudio;
                         }
                         if (item.long == "1") {
                             item.showTime = "1";
                             item.date = utils.showMsgDate(Number(item.userUpdateTime));
                             this.setData({
                                 showTime: Number(item.userUpdateTime)
                             })
                         }
                         this.data.adminData.unshift(item)
                     }else{
                        if (item.long == "1") {
                             item.showTime = "1";
                             item.date = utils.showMsgDate(Number(item.userUpdateTime));
                             this.setData({
                                 showTime: Number(item.userUpdateTime)
                             })
                         }
                         if (this.data.bubbleList.length >= 3){
                             this.data.bubbleList.shift();
                         }
                         this.data.bubbleList.push(item);
                     }
                  })
                  if (this.data.cgnames.length > 0) {
                    this.data.adminData.map((item, index) => {
                      let oldid = item.from;
                      this.data.cgnames.map((item2,index2)=>{
                        console.log(oldid)
                        if (item2.accid == oldid){
                          this.data.adminData[index].fromNick = item2.tsname;
                        }
                      })
                    })
                  }
                  this.setData({
                      adminData: this.data.adminData,
                      bubbleList: this.data.bubbleList
                  })
                  if(bol == true){
                      this.scrollBottom();
                  }
              }
          }else{
            wx.hideLoading();            
            wx.showToast({
                title: '获取历史记录失败,请重试',
                icon: "none"
            })
          }
      }, err => {
          this.isTop = true;            
          wx.showToast({
              title: '获取历史记录失败，网络错误',
              icon: "none"
          })
      })
  },
  //用户消息模块
  //监听用户输入
  userInp:function(e){
     this.setData({
         userText:e.detail.value
     })
     if (e.detail.cursor>0){
         this.setData({
             userDis:false
         })
     }else{
         this.setData({
             userDis: true
         })
     }
  },
  //滚动到底
  scrollBottom:function(){
      wx.createSelectorQuery().select('#msgsView').boundingClientRect(res=>{
          wx.pageScrollTo({
              scrollTop:res.height,
              duration:0
          });
      }).exec()
  },
  //用户评论
  userSend:function(){
      let str = this.data.userText;
      let opt = {
          type:'text',
          content:str,
          custom:{
              role:this.data.role
          }
      }
      this.setData({
          userText: '',
          userDis: true
      })
      this.sendRoomMsgs(opt);
  },
  //项目方消息模块
  //监听项目方输入
  adminchange:function(e){
      this.setData({
          adminval:e.detail.value
      })
      if (e.detail.cursor > 0){
          this.setData({
            adminDis:true
          })
      }else{
        this.setData({
            adminDis: false
        })
      }
  },
  //项目方文字
  adminSend: function () {
      let str = this.data.adminval;
      let opt = {
          type: 'text',
          content: str,
          custom: {
              role: 2
          }
      }
      this.setData({
          adminval: '',
          adminDis: false
      })
      this.sendRoomMsgs(opt);
  },
  //选择图片
  selectImg:function(){
      wx.chooseImage({
          count: 1, // 
          sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
          sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
          success: (res)=>{
              // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
              let path = res.tempFilePaths[0];
              let role = {role:2};
              glob.nim.sendFile({
                  type:'image',
                  wxFilePath:path,
                  custom:JSON.stringify(role),
                  done:this.sendFileMsg
              })
          }
      })
  },
  //文件消息发送结果
  sendFileMsg:function(err,msg){
      if(err){
          wx.showToast({
              title: '消息发送失败,请重试~',
              icon:'none'
          })
          console.log(err)
          glob.nim.connect();
      }else{
          console.log(msg)
          let user = wx.getStorageSync('user_msg'); 
         if(msg.type =='audio'){
             msg.file.dur = Math.ceil(Number(msg.file.dur)/1000);
             msg.audioImg = playAudio;
         }
         let time = Number(msg.userUpdateTime);
         if (time - this.data.showTime >= 300) {
             msg.long = "1";
             msg.date = utils.showMsgDate(time);
         }
         msg.fromNick = user.nickname;
         msg.fromAvatar = user.avatar;
         this.data.adminData.push(msg);
         if (this.data.cgnames.length > 0) {
           this.data.adminData.map((item, index) => {
             let oldid = item.from;
             this.data.cgnames.map((item2, index2) => {
               console.log(oldid)
               if (item2.accid == oldid) {
                 this.data.adminData[index].fromNick = item2.tsname;
               }
             })
           })
         }
         this.setData({
             adminData: this.data.adminData
         })
         this.scrollBottom();
      }
  },
  //播放音频
  playAudio:function(e){
      let src =  e.currentTarget.dataset.url;
      let id = e.currentTarget.dataset.id;
      if(src == this.data.currurl){
          innerAudioContext.stop();
          this.data.adminData.map((res,index)=>{
              if (res.idClient == id){
                  res.audioImg = playAudio;
              }
          })
          this.setData({
              currurl:"",
              adminData:this.data.adminData
          })
      }else{
          innerAudioContext.src = src;
          innerAudioContext.play();
          this.data.adminData.map((res, index) => {
              if (res.idClient == id) {
                  res.audioImg = playAudioGif;
              }else{
                  res.audioImg = playAudio;
              }
          })
          this.setData({
              currurl: src,
              adminData: this.data.adminData
          })
      }
  },
  //预览图片
  priewMsg:function(e){
      wx.previewImage({
          urls: [
              e.currentTarget.dataset.url
          ]
      })
  },
  //跳转讨论页面
  jumpDis:function(){
     let room_addr = JSON.stringify(this.room_addr);
     innerAudioContext.stop();
     this.data.adminData.length=0;
     this.isTop = false;
     this.setData({
         adminData: this.data.adminData,
         bubbleList:[],
         lid:""
     })
     glob.nim.disconnect();
     if(this.data.isComplete==true){
       wx.navigateTo({
         url: '../discuss/discuss?role=' + this.data.role + '&title=' + this.title + '&queryId=' + this.data.queryId + '&roomid=' + this.roomid + '&room_addr=' + room_addr + "&type=old"
       })
     }else{
       wx.navigateTo({
         url: '../discuss/discuss?role=' + this.data.role + '&title=' + this.title + '&queryId=' + this.data.queryId + '&roomid=' + this.roomid + '&room_addr=' + room_addr
       })
     }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
      console.log("退出");
      glob.nim.disconnect();
      innerAudioContext.stop();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  },
})